﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;

////using System.Linq;
//using System.Threading.Tasks;
using System.Data;
using System.Text.RegularExpressions;


namespace Reports
{
    class Program
    {
        //static DataSetToExcel dataSetToExcel = new DataSetToExcel();
        static DataTableToExcel toexcel = new DataTableToExcel();
        //Regex re = new Refex(@"/(\"/mini_)([^\s\.]#\.)(aspx\")");
        static Regex startReg = new Regex(@"\{StartTime\[(\d)\[0-4]}");//[\$]
        static Regex endReg = new Regex(@"\{EndTime\[(\d)[0-4]}");
        static Regex day = new Regex(@"\d");
        static void Main(string[] args)
        {

            //1. 拿到报表
            //2. 发送报表

            try
            {

                //string s = "fsdfsdfsdfsdfsdfs{StartTime[7]}";
                //day
                //Match m = startReg.Match(s);//.Result(@"{[(\d)]}");
                //int a = 1;
                #region
                MailSender mail = new MailSender();
                string[] files = new String[1];
                string sql = string.Empty;
                string rptName = string.Empty;
                Match match;

                //循环 所有要发的报表
                foreach (Report item in MailConfig.Rptlist)
                {

                    // 判断是否启用
                    if (!item.Enable)
                        continue;

                    if (item.Day.Contains(Convert.ToInt32(DateTime.Now.DayOfWeek).ToString()) &&
                         item.Hour.Contains(Convert.ToInt32(DateTime.Now.Hour).ToString()))
                    {

                        rptName = item.RptName.Replace("{now}", DateTime.Now.ToString("yyyyMMdd"));

                        //sql = item.SQLString.Replace("{now}", DateTime.Now.ToString("yyyy-MM-dd")).Replace("{StartTime}",
                        //DateTime.Now.ToString("yyyy-MM-dd")).Replace("{EndTime}", DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"));
                        sql = item.SQLString.Replace("{now}", DateTime.Now.ToString("yyyy-MM-dd"));//.Replace("0x3C", "<");
                        if (startReg.IsMatch(sql))
                        {
                            match = startReg.Match(sql);
                            sql = sql.Replace(match.ToString(), DateTime.Now.AddDays(-Convert.ToInt16(day.Match(match.ToString()).ToString())).ToString("yyyy-MM-dd"));
                        }

                        if (endReg.IsMatch(sql))
                        {
                            match = endReg.Match(sql);
                            sql = sql.Replace(match.ToString(), DateTime.Now.AddDays(Convert.ToInt16(day.Match(match.ToString()).ToString())).ToString("yyyy-MM-dd"));
                        }

                        //DataSet ds;
                        DataTable dt;
                        switch (item.DB)
                        {
                            case "WEB":
                                dt = DbHelperSQL.SelectRowsTest(sql, BaseConfig.Web).Tables[0];
                                break;
                            case "DB1":
                                dt = DbHelperSQL.SelectRowsTest(sql, BaseConfig.DB1).Tables[0];
                                break;
                            case "DB2":
                                dt = DbHelperSQL.SelectRowsTest(sql, BaseConfig.DB2).Tables[0];
                                break;
                            default://WEB
                                dt = DbHelperSQL.SelectRowsTest(sql, BaseConfig.Web).Tables[0];
                                break;
                        }



                        //文件存储路径
                        string repdizhi = BaseConfig.BasePath + DateTime.Now.ToString("yyyyMMdd");
                        //string repdizhi = BaseConfig.BasePath;
                        if (!System.IO.Directory.Exists(repdizhi))
                        {
                            System.IO.Directory.CreateDirectory(repdizhi);
                        }


                        //将报表数据生成文件
                        // if (ds != null && ds.Tables[0].Rows.Count > 0)
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            //string n = ds.Tables[0].Columns[0].ColumnName; 

                            //文件名
                            string Filexls = repdizhi + "\\" + rptName + ".xlsx";
                            if (System.IO.File.Exists(Filexls))
                            {
                                Filexls = repdizhi + "\\" + rptName + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xlsx";
                            }

                            #region datatable 转义

                            for (int i = 0; i < dt.Columns.Count; i++)
                            {
                                //确保都有映射的情况
                                //dt.Columns[i].ColumnName = MailConfig.ht_columnsmap[dt.Columns[i].ColumnName.ToUpper()].ToString();

                                //不确定都有映射
                                if (MailConfig.ht_columnsmap.Contains(dt.Columns[i].ColumnName.ToUpper()))
                                    dt.Columns[i].ColumnName = MailConfig.ht_columnsmap[dt.Columns[i].ColumnName.ToUpper()].ToString();

                            }
                            #endregion

                            //生成报表文件
                            //DataSetToExcel.doExport(ds, "报表", Filexls);
                            
                            //toexcel.ToExport(dt, Filexls);

                            //程序杀掉进程
                            toexcel.KillExcelProcess();
                            toexcel.OutputExcel(dt, rptName, repdizhi);
                            toexcel.KillExcelProcess();


                            //准备邮件附件
                            //files[0] = "D:\\test.txt";
                            //files[0] = BaseConfig.BasePath + DateTime.Now.ToString("yyyyMMdd") + "\\" + item.RptName + ".xlsx";
                            files[0] = Filexls;

                            //填充邮件内容 并发邮件 
                            mail.SetMail(item.RptTo, rptName, 
                                MailConfig.EmailContentTemp.Replace("{repName}", rptName), files);
                        }
                    }
                }
                #endregion

            }
            catch (Exception ex)
            {
                Log.WriteLog(ex);
            }

            //System.Threading.Thread.Sleep(5000);
        }
    }
}